using System;
using System.ComponentModel;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
using System.Windows.Input;

namespace AR.ViewModels.Commands
{
    public class UpdateSelectedCandidat : ICommand
    {
        private readonly HomeViewModel viewModel;

        public UpdateSelectedCandidat(HomeViewModel viewModel)
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                WebContext.Current.Authentication.LoggedIn += AuthenticationLoggedIn;
                WebContext.Current.Authentication.LoggedOut += AuthenticationLoggedOut;
                viewModel.PropertyChanged += ViewModelPropertyChanged;
            }

            this.viewModel = viewModel;
        }

        void ViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "SelectedCandidat")
            {
                CanExecuteChanged.Invoke(this, new EventArgs());
            }

        }

        private void AuthenticationLoggedOut(object sender, AuthenticationEventArgs e)
        {
            if (CanExecuteChanged != null)
                CanExecuteChanged.Invoke(this, new EventArgs());
        }

        private void AuthenticationLoggedIn(object sender, AuthenticationEventArgs e)
        {
            if (CanExecuteChanged != null)
                CanExecuteChanged.Invoke(this, new EventArgs());
        }

        public bool CanExecute(object parameter)
        {
            return WebContext.Current.User.IsAuthenticated
                   && viewModel.SelectedCandidat != null;

        }

        public void Execute(object parameter)
        {
            viewModel.SubmitChanges();
        }

        public event EventHandler CanExecuteChanged;
    }
}